﻿using com.ruovea.dto;
using com.ruovea.gogs.entity;
using com.ruovea.gogs.service;
using com.ruovea.utilty;
using com.ruovea.utilty.EnumExtension;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace GogsWeb.Api.Controllers
{
    /// <summary>
    /// 公共方法 可扩展
    /// </summary>
    [ApiController]
    //[AuthorizeAttribute]
    [Route("api/[controller]")]
    public class BaseController<T> : BaseResponse where T : class, new()
    {
        #region 请求响应
        /// <summary>
        /// 返回成功消息
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns></returns>
        protected virtual IActionResult ToJsonResult(object data)
        {
            return Content(data.ToJson());

        }
        /// <summary>
        /// 返回成功消息
        /// </summary>
        /// <param name="info">消息</param>
        /// <returns></returns>
        protected virtual IActionResult Success(string info)
        {
            return Content(new ResParameter { code = ResponseCode.Status, msg = info }.ToJson());
        }

        /// <summary>
        /// 返回成功数据
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns></returns>
        protected virtual ActionResult Success(object data)
        {
            return Content(new ResParameter { code = ResponseCode.Status, msg = ResponseCode.Status.GetEnumText(), data = data }.ToJson());
        }

        /// <summary>
        /// 返回成功消息
        /// </summary>
        /// <param name="info">消息</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        protected virtual ActionResult Success(string info, object data)
        {
            return Content(new ResParameter { code = ResponseCode.Status, msg = info, data = data }.ToJson());
        }

        /// <summary>
        /// 返回失败消息
        /// </summary>
        /// <param name="info">消息</param>
        /// <returns></returns>
        protected virtual ActionResult Fail(string info)
        {
            return Content(new ResParameter { code = ResponseCode.ParameterError, msg = info }.ToJson());
        }
        /// <summary>
        /// 返回失败消息
        /// </summary>
        /// <param name="info">消息</param>
        /// <param name="data">消息</param>
        /// <returns></returns>
        protected virtual ActionResult Fail(string info, object data)
        {
            return Content(new ResParameter { code = ResponseCode.ParameterError, msg = info, data = data }.ToJson());
        }
        #endregion

        /// <summary>
        /// 服务
        /// </summary>
        public BaseServer<T> service;

        /// <summary>
        /// 初始化
        /// </summary>
        public BaseController()
        {
            service = new BaseServer<T>();
        }

        #region Base method
        /// <summary>                                                                   
        /// 根据主键获取资源                                                                 
        /// </summary>                                                                  
        /// <param name="id"></param>                                                 
        /// <returns></returns>                                                         
        //[ApiExplorerSettings(IgnoreApi = true)]
        [HttpGet]
        public virtual async Task<IActionResult> Get(string id)
        {
            var resultData = await ctx.DB.GetSimpleClient<T>().GetByIdAsync(id); ;
            return Success(resultData);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        //[ApiExplorerSettings(IgnoreApi = true)]
        [HttpPost("query")]
        public virtual async Task<IActionResult> Post([FromBody] QueryData query)
        {
            if (query == null) query = new QueryData { page = 1, pageSize = 15 };
            Pagination parms = new Pagination { page = query.page, rows = query.pageSize };

            if (parms.page <= 0) parms.page = 1;
            if (parms.rows <= 0 || parms.rows > 10000) parms.rows = 25;

            PageData<List<T>> resultData=new PageData<List<T>> ();
            if (query.where == null || query.where.Count > 0)
            {
                resultData.data = await service.GetPagesAsync(parms);
            }
            else
            {
                var colName = typeof(T).GetProperties().Select(x => x.Name);
                foreach (var v in query.where)
                {
                    if (!colName.Contains(v.FieldName))
                        return Fail($"{v.FieldName}不是合法存在的字段.");
                }

                List<IConditionalModel> querys = new List<IConditionalModel>();
                foreach (var t in query.where)
                    querys.Add(new ConditionalModel { FieldName = t.FieldName, FieldValue = t.FieldValue, ConditionalType = (SqlSugar.ConditionalType)t.ConditionalType });

                resultData.data=await ctx.DB.Queryable<T>().Where(querys).ToPageAsync(parms);
            }
            resultData.total = parms.records;
            return Success(resultData);
        }

        /// <summary>
        /// 新建资源
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>

        //[ApiExplorerSettings(IgnoreApi = true)]
        [HttpPost]
        public virtual async Task<IActionResult> Post([FromBody] T value)
        {
            var resultData = await service.AddAsync(value);
            return Success(resultData);
        }

        /// <summary>
        /// 更新资源
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>

        //[ApiExplorerSettings(IgnoreApi = true)]
        [HttpPut]
        public virtual async Task<IActionResult> Put([FromBody] T value)
        {
            var resultData = await service.UpdateAsync(value);
            return Success(resultData);
        }

        /// <summary>                                                                   
        /// 删除资源                                                                    
        /// </summary>                                                                  
        /// <param name="id"></param>    
        //[ApiExplorerSettings(IgnoreApi = true)]
        [HttpDelete]
        public virtual async Task<IActionResult> Delete(string id)
        {
            var resultData = await service.DeleteAsync(id);
            return Success(resultData);
        }
        #endregion
    }
}
